<?php
class Login_wx extends CI_Controller
{	
	public $school_id;
	function __construct() {
        parent::__construct();
        $url_wap = 'http://'.$_SERVER['HTTP_HOST'];
		$school_info = get_field_by_where("o2o_school", "id", "url_wap='{$url_wap}'");
		$this->school_id = $school_info['id'];
    }
	
	public function index ()
	{
		//判断用户是否关注
		/*
		$token = 'SN-XNO3C3RBL1IPlDCKfbzn8AZYpi23vHGFSRYBpbFnOzu4YlrWO2bXEgmugBIFuurarbSqxZRsZcmfMNbKO3v_YEBr6PjBUGn2jDtjagCs';
		$appid = "wxa547532942ba8ef1";
		$secret = "fff269bc6b00780886f0afca0e833502";
		$code = $_GET["code"];
		$get_token_url = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token='.$token.'&next_openid=';
		$ch = curl_init();
		curl_setopt($ch,CURLOPT_URL,$get_token_url);
		curl_setopt($ch,CURLOPT_HEADER,0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
		$res = curl_exec($ch);
		curl_close($ch);
		$json_obj = json_decode($res,true);
		
		
		print_r($json_obj['data']);
		
		*/
		
		//微信自动登录url
		//$redirect_uri = urlencode("http://www.comefee.com/index.php");
			
		//$login_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxa547532942ba8ef1&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
		
		//获取微信配置
		/*$this->load->model('Syswxconfig_model');
		$wx_config = $this->Syswxconfig_model->get_wxconfig();
		if(empty($wx_config)) {
			header("Location:/logreg");exit;
		}*/
		$wx_config = get_field_by_where("o2o_school_wx_config", "app_id, app_secret", "school_id='{$this->school_id}'");
		if(empty($wx_config['app_id']) || empty($wx_config['app_secret'])){
			show_message("/logreg", "该网校微信登录未设置完整");
			exit;
		}
		$APPID=$wx_config['app_id'];
		// $REDIRECT_URI=$wx_config['login_redirect_uri'];//'http://www.comefee.com/index.php/login_wx/callback?w=';
		$REDIRECT_URI = 'http://' . $_SERVER['HTTP_HOST'] . '/login_wx/callback';
		$state = "2";

		$scope='snsapi_base';
		//'snsapi_userinfo'//需要授权
		//'snsapi_base'//不需要授权
		$url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$APPID.'&redirect_uri='.urlencode($REDIRECT_URI).'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
		header("Location:".$url);


	}

	// public function upwx()
	// {
	// 	$appid = "wxa547532942ba8ef1";
	// 	$secret = "fff269bc6b00780886f0afca0e833502";
	// 	$code = $_GET["code"];
	// 	$get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';
	// 	$ch = curl_init();
	// 	curl_setopt($ch,CURLOPT_URL,$get_token_url);
	// 	curl_setopt($ch,CURLOPT_HEADER,0);
	// 	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
	// 	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
	// 	$res = curl_exec($ch);
	// 	curl_close($ch);
	// 	$json_obj = json_decode($res,true);
	// 	//print_r($json_obj);
	// 	//
		
	// 	//根据openid和access_token查询用户信息
	// 	$access_token = $json_obj['access_token'];
	// 	$openid = $json_obj['openid'];
	// 	$get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
		
	// 	$ch = curl_init();
	// 	curl_setopt($ch,CURLOPT_URL,$get_user_info_url);
	// 	curl_setopt($ch,CURLOPT_HEADER,0);
	// 	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
	// 	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
	// 	$res = curl_exec($ch);
	// 	curl_close($ch);
		
	// 	//解析json
	// 	$user_obj = json_decode($res,true);
		
	// 	//print_r($user_obj);
			
		
	// 	$this->load->helper('url');
	// 	$this->load->library('session');
	// 	//查询用户信息
	// 	$this->load->model('user_model');
	// 	$user = $this->user_model->get_user_by_openid($json_obj['openid']);
	// 	if(empty($user))
	// 	{
	// 		//新用户存入数据库($parent1,$wx_openid,$nickname,$sex,$province,$city,$country,$headimgurl,$unionid)
	// 		$userid = $this->user_model->add_wx_user($wid,$json_obj['openid'],$user_obj['nickname'],$user_obj['sex'],$user_obj['province'],$user_obj['city'],$user_obj['country'],$user_obj['headimgurl'],'');
			
	// 		//添加Session
	// 		$userdata = array(
	// 				'userid' =>$userid,
	// 				'userphone'  => '',
	// 				'openid' => $json_obj['openid'],
	// 				'email'     => '',
	// 				'logged_in' => TRUE
	// 		);
	// 		$this->session->set_userdata($userdata);
			
	// 		//跳转页面
	// 		redirect(base_url()."index.php/my/info");
			
			
	// 	}else 
	// 	{
	// 		if(empty($user[0]->nickname))
	// 		{
	// 			//更新微信资料
	// 			$this->user_model->update_wx_info($user[0]->user_id,$user_obj['nickname'],$user_obj['headimgurl'],$user_obj['sex'],$user_obj['province'],$user_obj['city'],$user_obj['country']);
	// 		}
			
	// 		redirect(base_url()."index.php/my/info");
	// 	}
	// }

	
	public function callback()
	{
		/*$this->load->model('Syswxconfig_model');
		$wx_config = $this->Syswxconfig_model->get_wxconfig();
		if(empty($wx_config)) {
			header("Location:/logreg");exit;
		}*/
		$wx_config = get_field_by_where("o2o_school_wx_config", "app_id, app_secret", "school_id='{$this->school_id}'");
		if(empty($wx_config['app_id']) || empty($wx_config['app_secret'])){
			show_message("/logreg", "该网校微信登录未设置完整");
			exit;
		}
		$wid = $this->input->get('w');
		$callback_url = $this->input->get('cb');
		// print_r($wid);
		// exit();
		//获取openid 和access_token
		$appid = $wx_config['app_id'];
		$secret = $wx_config['app_secret'];
		$code = $_GET["code"];
		$get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';
		// echo $get_token_url;
		$ch = curl_init();
		curl_setopt($ch,CURLOPT_URL,$get_token_url);
		curl_setopt($ch,CURLOPT_HEADER,0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
		$res = curl_exec($ch);
		curl_close($ch);
		$json_obj = json_decode($res,true);
		
		//
		
		//根据openid和access_token查询用户信息
		$access_token = $json_obj['access_token'];
		$openid = $json_obj['openid'];
		$get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
		
		$ch = curl_init();
		curl_setopt($ch,CURLOPT_URL,$get_user_info_url);
		curl_setopt($ch,CURLOPT_HEADER,0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
		$res = curl_exec($ch);
		curl_close($ch);

		// print_r($openid);exit;
		
		//解析json
		$user_obj = json_decode($res,true);
		
		// print_r($user_obj);			
		
		$this->load->helper('url');
		$this->load->library('session');
		//查询用户信息
		$this->load->model('User_model');
		

		$user = $this->User_model->get_user_by_openid($openid);

		if(empty($user)){
			$url = "/logreg?openid=".$openid;
			// print_r($url);exit;
			//去绑定用户
			header("Location:".$url);exit;
			
		}else 
		{
			//去绑定用户
			//设置cookie
            $user_data = array(
                'id' => $user['id'],
                'head_image' => $user['head_image_url'],
                'user_name' => $user['login_name'],
                'mobile' => $user['mobile'],
                'logged_in' => 1);
            $this->session->set_userdata('user_data', $user_data);

			header("Location:/");exit;
			// if(empty($user[0]->nickname))
			// {
			// 	//更新微信资料
			// 	$this->user_model->update_wx_info($user[0]->user_id,$user_obj['nickname'],$user_obj['headimgurl'],$user_obj['sex'],$user_obj['province'],$user_obj['city'],$user_obj['country']);
			// }
			// //添加Session
			// $userdata = array(
			// 		'userid' =>$user[0]->user_id,
			// 		'userphone'  => $user[0]->user_phone,
			// 		'openid' => $json_obj['openid'],
			// 		'email'     => $user[0]->user_email,
			// 		'logged_in' => TRUE
			// );
			// $this->session->set_userdata($userdata);
			
			// if(empty($callback_url))
			// {
			// 	//跳转页面
			// 	redirect(base_url()."index.php?w=".$user[0]->user_id);
			// }
			// else
			// {
			// 	redirect($callback_url."&w=".$user[0]->user_id);
			// }
			//跳转页面
			//redirect(base_url()."index.php?w=".$user[0]->user_id);
		}
		
		
		//跳转页面
	
		//print_r($this->session);
		
			
		
	}
}